package com.app.common.net.ly

import com.app.common.net.BaseProtocol
import com.app.common.net.HttpProtocol
import org.jsoup.nodes.Document

class ApiLyService(ip: String = API_HOST_IP_LY) : BaseProtocol {

    override fun release() {
        httpProtocol.release()
    }

    companion object {
        const val API_HOST_IP_LY = "192.168.1.254"
    }

    class Response(val content:String,val code:Int = 0){
        val success = code == 0

        fun attr(name: String):String{
            if (!success) {
                return ""
            }
            return content.sub("<$name>","</$name>")
        }
    }

    private val httpProtocol = HttpProtocol(true)
    private   val converter = LyApiResponseConverter()
    private val host = "http://$ip/"
    private val baseUrl = "$host/"

    suspend fun <T> asyncSendCommandWith(cmd: Any,par:Any? = null,str:Any? = null,converter: HttpProtocol.Converter<T>): T {
        val pm = when {
            par!=null -> "&par=$par"
            str!=null -> "&str=$str"
            else -> ""
        }
        return try {
            httpProtocol.getAsync(baseUrl, "custom=1&cmd=$cmd$pm",converter).await()
        }catch (e:Exception){
            e.printStackTrace()
            converter.onConvert(null)
        }
    }

    suspend  fun <T> asyncSendCommand(cmd: Int,vararg query:String,converter:(Document?)->T): T {
        val convert = object :LyApiResponseElements<T>(converter){}
        val pm = if(query.isEmpty()) "cmd=$cmd" else "cmd=$cmd&" + query.joinToString("&")
        return try {
            httpProtocol.getAsync(baseUrl, "custom=1&$pm",convert).await()
        }catch (e:Exception){
            e.printStackTrace()
            converter(null)
        }
    }


    suspend fun asyncSendCommandWith(cmd: Any,par:Any? = null,str:String? = null): Response {
        val pm = if (par!=null) {
            "&par=$par"
        }else if (str!=null) {
            "&str=$str"
        }else{
            ""
        }
        return try {
            httpProtocol.getAsync(baseUrl, "custom=1&cmd=$cmd$pm",converter).await()
        }catch (e:Exception){
            e.printStackTrace()
            Response("",-1)
        }
    }

}